<template>
  <div class="app-container">
<!--    &lt;!&ndash; 顶部操作栏 &ndash;&gt;-->
<!--    <div class="search-bar">-->
<!--      <el-form ref="queryFormRef" :model="queryParams" :inline="true">-->
<!--        <el-form-item label="关键字" prop="keywords">-->
<!--          <el-input-->
<!--              v-model="queryParams.keywords"-->
<!--              placeholder="菜单名称"-->
<!--              clearable-->
<!--              @keyup.enter="handleQuery"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>-->
<!--          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </div>-->

    <el-card shadow="never" class="search-table">
      <div class="mb-10px">
        <el-button
            type="success"
            icon="plus"
            @click="handleOpenDialog('0')"
        >
          新增
        </el-button>
      </div>

      <el-table
          :data="menuTableData"
          row-key="menuId"
          highlight-current-row
          v-loading="loading"
          @row-click="handleRowClick"
          :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <component class="icons" :is="scope.row.menuIcon"></component>
            {{ scope.row.menuName }}
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">菜单</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路由名称" align="left" width="150" prop="menuName" />
        <el-table-column label="路由路径" align="left" width="150" prop="routerPath" />
        <el-table-column label="组件路径" align="left" width="150" prop="componentsPath" />
        <el-table-column label="权限标识" align="center" width="100" prop="perm" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.visible === 'Y'" type="success">显示</el-tag>
            <el-tag v-else type="info">隐藏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" width="80" prop="displayOrder" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
                v-if="scope.row.type === MenuTypeEnum.CATALOG || scope.row.type === MenuTypeEnum.MENU"
                type="primary"
                link
                size="small"
                icon="plus"
                @click.stop="handleOpenDialog(scope.row.menuId)"
            >
              新增
            </el-button>

            <el-button
                type="primary"
                link
                size="small"
                icon="edit"
                @click.stop="handleOpenDialog(undefined, scope.row.menuId)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                link
                size="small"
                icon="delete"
                @click.stop="handleDelete(scope.row.menuId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="45%"
        @close="handleCloseDialog"
    >
      <el-form :disabled="disableFlag" ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
              v-model="formData.parentId"
              placeholder="选择上级菜单"
              :data="menuOptions"
              filterable
              check-strictly
              :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="formData.menuName" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleMenuTypeChange">
            <el-radio :value="MenuTypeEnum.CATALOG">目录</el-radio>
            <el-radio :value="MenuTypeEnum.MENU">菜单</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item
            v-if="formData.type === MenuTypeEnum.CATALOG || formData.type === MenuTypeEnum.MENU"
            prop="routerPath"
        >
          <template #label>
            <div class="flex-y-center">
              路由路径
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  定义应用中不同页面对应的 URL 路径，目录需以 / 开头，菜单项不用。例如：系统管理目录
                  /system，系统管理下的用户管理菜单 user。
                </template>
                <el-icon class="ml-1 cursor-pointer">
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input
              v-if="formData.type === MenuTypeEnum.CATALOG"
              v-model="formData.routerPath"
              placeholder="system"
          />
          <el-input v-else v-model="formData.routerPath" placeholder="user" />
        </el-form-item>

        <el-form-item v-if="formData.type === MenuTypeEnum.MENU" prop="componentsPath">
          <template #label>
            <div class="flex-y-center">
              组件路径
              <el-tooltip placement="bottom" effect="light">
                <template #content>
                  组件页面完整路径，相对于 src/views/，如 system/user/index，需要加.vue后缀
                </template>
                <el-icon class="ml-1 cursor-pointer">
                </el-icon>
              </el-tooltip>
            </div>
          </template>

          <el-input v-model="formData.componentsPath" placeholder="system/user/index" style="width: 95%">
            <template v-if="formData.type === MenuTypeEnum.MENU" #prepend>src/views/</template>
<!--            <template v-if="formData.type === MenuTypeEnum.MENU" #append>.vue</template>-->
          </el-input>
        </el-form-item>

        <el-form-item prop="visible" label="显示状态">
          <el-radio-group v-model="formData.visible">
            <el-radio :value="'Y'">显示</el-radio>
            <el-radio :value="'N'">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="displayOrder">
          <el-input-number
              v-model="formData.displayOrder"
              style="width: 100px"
              controls-position="right"
              :min="0"
          />
        </el-form-item>

        <el-form-item label="图标" prop="menuIcon">
          <!-- 图标选择器 -->
          <icons-select v-model="formData.menuIcon" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disableFlag" type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteFlag" @close="deleteCloseDialog" center title="警告" style="width: 420px;height: 148px">
      <component class="icons" is="WarningFilled" style="width: 25px;height: 25px;color: #ff9a2e"/>
      <span> 确认删除用户?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="deleteSubmit">确 定</el-button>
          <el-button @click="deleteFlag = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted,toRefs } from 'vue';
import {deleteByMenuId, deleteUser, getAllMenu, getMenuById, insertMenu, updateMenu} from '@/api/index.js';
import IconsSelect from '../components/icons/iconsSelect.vue'
import { ElMessage } from 'element-plus';
const menuOptions = ref([]);

const queryParams = reactive({});
const loading = ref(false);
const selectedMenuId = ref();
const menuTableData = ref([]);
const menuFormRef = ref(null);
const disableFlag = ref(false);

const MenuTypeEnum = {
  CATALOG: 'catalog', // 目录
  MENU: 'menu' // 菜单
};
// 初始菜单表单数据
const initialMenuFormData = ref({
  menuId: undefined,
  parentId: '0',
  visible: 'Y',
  displayOrder: 1,
  type: MenuTypeEnum.MENU, // 默认菜单
  params: []
});


const rules = reactive({
  parentId: [{ required: true, message: "请选择父级菜单", trigger: "blur" }],
  menuName: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
  routerPath: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  componentsPath: [{ required: true, message: "请输入组件路径", trigger: "blur" }],
  visible: [{ required: true, message: "请选择显示状态", trigger: "change" }],
  menuIcon: [{ required: true, message: "请选择icon图标", trigger: "blur" }],
});
// 菜单表单数据
const formData = ref({...initialMenuFormData.value });

const dialog = reactive({
  title: '新增菜单',
  visible: false
});
const handleQuery = () => {
  console.log('搜索');
  getAllMenu().then((data) => {
    if (data.data.code === 200) {
      menuTableData.value = data.data.data;
      console.log(data.data.data.visible === 'Y');
      console.log(menuTableData);
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(()=>{
    ElMessage.error("执行异常")
  }).finally(() => {
    loading.value = false;
  });
};
const handleResetQuery = () => {
  console.log('重置');
};

const handleOpenDialog = (parentId, menuId) => {
  getAllMenu().then((data) => {
    if (data.data.code === 200) {
      menuOptions.value = [{ value: '0', label: '顶级菜单', children: convert(data.data.data) }];
    } else {
      ElMessage.error(data.data.msg);
    }
  }).then(() => {
    dialog.visible = true;
    // menuFormRef.value.clearValidate();
    if (menuId) {
      dialog.title = '编辑菜单';
      getMenuById(menuId).then((data) => {
        if (data.data.code === 200) {
          initialMenuFormData.value = { ...data.data.data };
          formData.value = data.data.data;
          formData.value.parentId = data.data.data.parentId.toString();
        } else {
          ElMessage.error(data.data.msg);
        }
      })
    } else {
      dialog.title = '新增菜单';
      formData.value.parentId = parentId ? parentId.toString() : '0';
    }
  }).catch(()=>{
    ElMessage.error("执行异常")
  });
};
const handleRowClick = (row) => {
  // selectedMenuId.value = row.menuId;
  formData.value = row;
  disableFlag.value = true;
  dialog.visible = true;
  dialog.title = "查看菜单";
  console.log(menuTableData.value)
};

const deleteMenuId = ref();
const deleteFlag = ref(false);
const handleDelete = (menuId) => {
  deleteMenuId.value = menuId;
  deleteFlag.value = true;
};

const deleteCloseDialog = () => {
  deleteMenuId.value = null;
  deleteFlag.value = false;
}

const deleteSubmit = () => {
  deleteByMenuId(deleteMenuId.value).then((data)=>{
    if(data.data.code === 200) {
      ElMessage.success(data.data.msg);
      deleteCloseDialog();
      handleQuery()
    }else {
      ElMessage.error(data.data.msg);
    }
  }).catch((error) =>{
    ElMessage.error("执行异常")
  })
}





const handleCloseDialog = () => {
  resetForm();
  disableFlag.value = false;
  dialog.visible = false;
};

const resetForm = () => {
  // menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = {
    menuId: undefined,
    parentId: '0',
    visible: 'Y',
    displayOrder: 1,
    type: MenuTypeEnum.MENU, // 默认菜单
    params: []
  };
};
const handleMenuTypeChange = () => {
  // 如果菜单类型改变
  if (formData.value.type!== initialMenuFormData.value.type) {
    if (formData.value.type === MenuTypeEnum.MENU) {
      // 目录切换到菜单时，清空组件路径
      if (initialMenuFormData.value.type === MenuTypeEnum.CATALOG) {
        formData.value.componentsPath = '';
      } else {
        // 其他情况，保留原有的组件路径
        formData.value.routerPath = initialMenuFormData.value.routerPath;
        formData.value.componentsPath = initialMenuFormData.value.componentsPath;
      }
    }
  }
};

/**
 * 提交表单
 */
function handleSubmit() {
  menuFormRef.value.validate((isValid) => {
    if (isValid) {
      const menuId = formData.value.menuId;
      if (menuId) {
        //修改时父级菜单不能为当前菜单
        if (formData.value.parentId === menuId) {
          ElMessage.error("父级菜单不能为当前菜单");
          return;
        }
        updateMenu(formData.value).then((data) =>{
          if(data.data.code === 200) {
            ElMessage.success(data.data.msg);
            handleCloseDialog();
            handleQuery();
          }else {
            ElMessage.error(data.data.msg);
          }
        }).catch((error) =>{
          ElMessage.error("执行异常")
        })
      } else {
        insertMenu(formData.value).then((data) =>{
          if(data.data.code === 200) {
            ElMessage.success(data.data.msg);
            handleCloseDialog();
            handleQuery();
          }else {
            ElMessage.error(data.data.msg);
          }
        }).catch((error) =>{
          ElMessage.error("执行异常")
        })
      }
    }
  });
}

function convert(arr) {
  return arr.map(item => {
    const newItem = {
      ...item,
      label: item.menuName,
      value: item.menuId
    };
    delete newItem.menuName;
    delete newItem.menuId;

    if (item.children) {
      newItem.children = convert(item.children);
    }
    return newItem;
  });
}

onMounted(()=>{
  handleQuery();
})

</script>

<style scoped>
.app-container {
  padding: 15px;
  height: 90%;
}

.search-bar {
  padding: 18px 0 0 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.table-container >.el-card__header {
  padding: calc(var(--el-card-padding) - 8px) var(--el-card-padding);
}

.icons {
  width: 15px;
  height: 15px;
}
.search-table{
  height: 100%;
}
.dialog-footer{
  text-align: center;
}
</style>